package com.kai.Controller;

import com.alibaba.fastjson.JSONObject;
import com.kai.Pojo.Books;
import com.kai.Service.BookService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {

    //自动装配bean根据id
    @Resource
    private BookService bookService;

    //将一些信息传递
    @Resource
    private DiscoveryClient client;

    //0.查看全部
    @RequestMapping("/allBook")
    public JSONObject list(){
        List<Books> list = bookService.queryAllBook();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",list);
        return jsonObject;
    }

    //1.根据id查看
    @RequestMapping("/queryBookById/{id}")
    public Books queryBookById(@PathVariable("id") int id){
        return bookService.queryBookById(id);
    }

    //2.添加(自增的不用设置id)
    @PostMapping("/addBook")
    public int addBook(@RequestBody Books books){
        System.out.println(books);
        return bookService.addBook(books);
    }

    //3.修改
    @RequestMapping("/updateBook")
    public int updateBook(@RequestBody Books book){
        System.out.println(book);
        return bookService.updateBook(book);
    }


    //4.删除：restFul风格进行传参
    @GetMapping("/del/{BookId}")
    public int delBook(@PathVariable int BookId){
        return bookService.deleteBookById(BookId);
    }

    //5.根据书名模糊查询
    @RequestMapping("/queryBookName/{bookName}")
    public JSONObject queryBookName(@PathVariable("bookName") String bookName){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",bookService.queryBookName(bookName));
        return jsonObject;
    }

    @RequestMapping("/discovery")
    public Object Discovery(){
        //得到所有注册的服务列表
        List<String> services = client.getServices();
        System.out.println("当前所有的微服务:" + services);

        //通过名字的到具体的实例化对象
        List<ServiceInstance> instances = client.getInstances("SpringCloud-Provider1");
        instances.forEach(x->{
            System.out.println(x.getHost()+"\t"+
                                x.getServiceId()+"\t"+
                                x.getPort()+"\t"+
                                x.getUri()+"\t"
            );
        });

        return client;
    }

}
